package com.android.pic;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.android.R;
import com.android.common.TextUtil;

public class PicUploadActivity extends Activity {
	/** Called when the activity is first created. */
	private ImageZoomView mZoomView;
	private ZoomState mZoomState;
	private Bitmap mBitmap;
	private SimpleZoomListener mZoomListener;
	private ProgressBar progressBar;
	private String picurl;
	// BitmapDrawable mBitmap2;

	private static String SDCARD = "/sdcard/";
	private String fileName = "networkimg1.jpg";
	private Button btn_downImg;
	private String message;
	Bitmap photo;

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressBar.setVisibility(View.GONE);
			mZoomView.setImage(mBitmap);
			// mZoomView.set
			mZoomState = new ZoomState();
			mZoomView.setZoomState(mZoomState);
			mZoomListener = new SimpleZoomListener();
			mZoomListener.setZoomState(mZoomState);
			mZoomView.setOnTouchListener(mZoomListener);
			resetZoomState();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_picview);
		mZoomView = (ImageZoomView) findViewById(R.id.zoomView);
		progressBar = (ProgressBar) findViewById(R.id.progress_large);
		progressBar.setVisibility(View.VISIBLE);
		Bundle bundle = getIntent().getExtras();
		 Log.e("photo<<<<1", String.valueOf(photo));
		if (bundle != null) {
			picurl = bundle.getString("picurl");
			 photo = bundle.getParcelable("data");
			 if (photo!=null) {
				 Log.e("photo<<<<2", String.valueOf(photo));
				 mZoomView.setImage(photo);
			}
			 Log.e("photo<<<<3", String.valueOf(photo));
			 
		}
		// picUrl
		ZoomControls zoomCtrl = (ZoomControls) findViewById(R.id.zoomCtrl);
		zoomCtrl.setOnZoomInClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				float z = mZoomState.getZoom() + 0.25f;
				mZoomState.setZoom(z);
				mZoomState.notifyObservers();
			}
		});
		zoomCtrl.setOnZoomOutClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				float z = mZoomState.getZoom() - 0.25f;
				mZoomState.setZoom(z);
				mZoomState.notifyObservers();
			}
		});

		btn_downImg = (Button) this.findViewById(R.id.btn_downImg);
		btn_downImg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mBitmap != null) {
					progressBar.setVisibility(View.VISIBLE);
					new Thread(saveFileRunnable).start();
				}
			}
		});
	}

	public static class ImageService {
		public static byte[] getImage(String path) throws Exception {
			// 构造一个URL对象 http://www.baidu.com/img/baidu_sylogo1.gif
			URL url = new URL(path);
			// 使用openConnection打开URL对象
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 使用Http协议，设置请求方式为GET
			conn.setRequestMethod("GET");
			// 设置链接超时异常，5s
			conn.setConnectTimeout(5 * 1000);
			// 通过输入流获取图片数据
			InputStream inStream = conn.getInputStream();
			// 返回图片的二进制数据
			return StreamTool.readInputStream(inStream);
		}
	}

	public static class StreamTool {
		/**
		 * 从输入流里面得到返回为二进制的数据
		 * 
		 * @param inStream
		 *            输入流
		 * @return byte[] 二进制数据
		 * @throws Exception
		 */
		public static byte[] readInputStream(InputStream inStream)
				throws Exception {
			// 构造一个ByteArrayOutputStream
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			// 设置一个缓冲区
			byte[] buffer = new byte[2048];
			int len = 0;
			// 判断输入流长度是否等于-1，即非空
			while ((len = inStream.read(buffer)) != -1) {
				// 把缓冲区的内容写入到输出流中，从0开始读取，长度为len
				outStream.write(buffer, 0, len);
			}
			// 关闭输入流
			inStream.close();
			return outStream.toByteArray();
		}
	}

	private Runnable saveFileRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				saveImg(getSDorInerMemPath());
				message = "图片保存成功！,存储路径：" + getSDorInerMemPath()
						+ TextUtil.formatName(picurl) + ".jpg";
			} catch (IOException e) {
				message = "图片保存失败！";
				e.printStackTrace();
			}
			messageHandler.sendMessage(messageHandler.obtainMessage());
		}
	};

	private Handler messageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			progressBar.setVisibility(View.GONE);

			Toast.makeText(PicUploadActivity.this, message, Toast.LENGTH_SHORT)
					.show();
		}
	};

	public String getSDorInerMemPath() {
		// File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			SDCARD = Environment.getExternalStorageDirectory()
					.getAbsolutePath();// 获取sdcard目录
		} else {
			SDCARD = Environment.getDataDirectory().getPath();// 获取跟目录
		}
		return SDCARD + "/inspur/";

	}

	// 保存图片方法
	public void saveImg(String fullPath) throws IOException {

		// 先判断目录是否存在
		File dir = new File(fullPath);
		if (!dir.exists()) { // 不存在则创建
			dir.mkdirs();
		}
		// 判断文件是否存在
		File image = new File(fullPath + TextUtil.formatName(picurl) + ".jpg");
		if (!image.exists()) { // 不存在则保存
			try {
				image.createNewFile();
				FileOutputStream fileOutputStream = new FileOutputStream(image);
				if (mBitmap.compress(Bitmap.CompressFormat.PNG, 100,
						fileOutputStream)) {
					fileOutputStream.flush();
				}
				fileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mBitmap != null)
			mBitmap.recycle();
		// mZoomView.setOnTouchListener(null);
		// mZoomState.deleteObservers();
	}

	private void resetZoomState() {
		mZoomState.setPanX(0.5f);
		mZoomState.setPanY(0.5f);
		mZoomState.setZoom(1f);
		mZoomState.notifyObservers();
	}
}
